package com.wjc.wjc.service;

import com.wjc.wjc.dao.StudentRepository;
import com.wjc.wjc.unity.Student;
import com.wjc.wjc.unity.StudentQury;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public Student login(String sno, String password) {
        return studentRepository.findBySnoAndPassword(sno, password);
    }

    @Override
    public Page<Student> listStudent(Pageable pageable, StudentQury studentQury) {
        return studentRepository.findAll(new Specification<Student>() {
            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(studentQury.getName()) && studentQury.getName() != null) {
                    predicates.add(cb.like(root.<String>get("name"), "%"+studentQury.getName()+"%"));
                }
                if (!"".equals(studentQury.getSno()) && studentQury.getSno() != null) {
                    predicates.add(cb.like(root.<String>get("sno"), "%"+studentQury.getSno()+"%"));
                }
                if (!"".equals(studentQury.getGrades()) && studentQury.getGrades() != null) {
                    predicates.add(cb.like(root.<String>get("grades"), "%"+studentQury.getGrades()+"%"));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    @Override
    public Student save(Student student) {
        student.setPassword("000");
        student.setPictureUrl("/images/avatar.png");
        return studentRepository.save(student);
    }

    @Override
    public void delete(Long id) {
        studentRepository.deleteById(id);
    }

    @Override
    public void resetPassword(Long id) {
        studentRepository.resetPwd(id);
    }

    @Override
    public void updatePwd(String password, String sno) {
        studentRepository.updatePwd(password, sno);
    }

    @Override
    public void updateIfor(String sex, String birthDate, String affiliation, String address,String sno) {
        studentRepository.updateInfor(sex, birthDate, affiliation, address, sno);
    }

    @Override
    public Student getOne(String sno) {
        return studentRepository.findBySno(sno);
    }
}
